<template>
  <div>
    <van-tabs>
      <van-tab title="表单信息">
        <div id="SiteSurvey">
          <div class="top">
            <img style="width:80%;margin: 0 auto;margin-bottom:10px;"
              src="https://nfzjszlb.jst.zj.gov.cn/serverfile/zheliban/icon/DSF/35.png" />
            <p>
              <span style="width:15%;display: inline-block;text-align: center;">申请信息</span>
              <span style="width:15%;display: inline-block;text-align: center;">现场踏勘</span>
              <span style="width:15%;display: inline-block;text-align: center;">定位放样</span>
              <span style="width:15%;display: inline-block;text-align: center;">基槽验线</span>
              <span style="width:15%;display: inline-block;text-align: center;">一层立模</span>
              <span style="width:15%;display: inline-block;text-align: center;">竣工验收</span>
            </p>
          </div>
          <div class="content">
            <div class="list">
              <van-form validate-first>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.HOMESTEADAREA" label="宅基地面积（m2）" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.HOUSEFLOORAREA" label="房基占地面积（m2）" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.CONSTRUCITONADDRESS" label="地址" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.EAST" label="东至" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.SOUTH" label="南至" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.WEST" label="西至" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.NORTH" label="北至" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field clickable readonly name="picker" :value="formData.YDLX | inUseName(ENUM.YDLXARR)" label="地类"
                    placeholder="请选择地类" @click="ENUM.YDLX = true" />
                  <van-popup v-model="ENUM.YDLX" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="ENUM.YDLXARR" value-key="DICNAME" @confirm="onConfirm2"
                      @cancel="ENUM.YDLX = false" />
                  </van-popup>
                </div>
                <div class="inputWrap" v-if="formData.YDLX == 17">
                  <van-field clickable readonly name="picker" :value="formData.DL_NYD | inUseName(ENUM.NYDARR)"
                    label="农用地" placeholder="请选择农用地" @click="ENUM.NYD = true" />
                  <van-popup v-model="ENUM.NYD" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="ENUM.NYDARR" value-key="DICNAME" @confirm="onConfirm5"
                      @cancel="ENUM.NYD = false" />
                  </van-popup>
                </div>

                <div class="inputWrap" v-if="formData.DL_NYD == 106">
                  <van-field v-model="formData.YDLX_NYD_QT" label="其他" placeholder="请填写其他" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field clickable readonly name="picker" :value="formData.APPLYTYPE | inUseName(ENUM.JFLXARR)"
                    label="建房类型" placeholder="请选择建房类型" @click="ENUM.JFLX = true" />
                  <van-popup v-model="ENUM.JFLX" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="ENUM.JFLXARR" value-key="DICNAME" @confirm="onConfirm1"
                      @cancel="ENUM.JFLX = false" />
                  </van-popup>
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.BUILDAREA" label="住房建筑面积（m2）" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.BUILDSTOREY" label="建筑层数（层）" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.BUILDHEIGHT" label="檐口高度（米）" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field clickable readonly :value="formData.STRUCTURETYPE | inUseName(ENUM.JGLXARR)" label="结构类型"
                    placeholder="请选择" @click="ENUM.JGLX = true" />
                  <van-popup v-model="ENUM.JGLX" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="ENUM.JGLXARR" value-key="DICNAME" @confirm="onConfirm3"
                      @cancel="ENUM.JGLX = false" />
                  </van-popup>
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.SPACING" label="日照间距" placeholder="请输入" />
                </div>
                <div class="inputWrap">
                  <span style="color: #FF0000;">*</span>
                  <van-field v-model="formData.EXTERIORCOLOR" label="外墙色彩" placeholder="请输入" />
                </div>
              </van-form>
            </div>
            <div v-for="(item, index) in fileData" :key="index" style="border-bottom: 1px solid #ebedf0">
              <template v-if="item.name == '坐标串'">
                <div style="display: flex;justify-content: space-between;">
                  <span style="font-size:16px;line-height:44px;"><span
                      style="color: #FF0000;margin-right:10px">*</span>坐标串</span>
                  <van-uploader @click-upload="getList(item)" @click-preview="lookFile" :after-read="afterRead"
                    :before-delete="delectFile" v-model="item.fileList" :max-count="1"
                    accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx" style="margin-top:10px;">
                    <van-button icon="plus" type="info" plain size="mini">上传TXT文件</van-button>
                  </van-uploader>
                </div>
              </template>
              <template v-else-if="item.name == '坐标文件'">
                <div style="display: flex;justify-content: space-between;">
                  <span style="font-size:16px;line-height:44px;"><span
                      style="color: #FF0000;margin-right:10px">*</span>坐标文件</span>
                  <van-uploader @click-upload="getList(item)" @click-preview="lookFile" :after-read="afterRead"
                    :before-delete="delectFile" v-model="item.fileList" :max-count="1"
                    accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx" style="margin-top:10px;">
                    <van-button icon="plus" type="info" plain size="mini">上传CAD文件</van-button>
                  </van-uploader>
                </div>
              </template>
              <template v-else>
                <p style="font-size:16px;line-height:44px;">
                  {{ item.name }}
                </p>
                <van-uploader @click-upload="getList(item)" :after-read="afterRead" :before-delete="delectFile"
                  v-model="item.fileList" multiple />
              </template>
            </div>
            <div style="margin:10px 0;background: #EEF5FF;padding:10px;">
              <p style="font-size:16px;font-weight: bold;margin:6px 0">测绘提示：</p>
              <p style="font-size:14px">
                测绘公司必须上传CAD文件和相关的坐标串文件，其中坐标串文件格式要求：文件为两列，第一列X轴坐标信息。第二列Y轴坐标信息，每行一组X轴、Y轴信息。坐标系必须使用2000国家大地坐标系。
              </p>
            </div>
          </div>
          <div @click="getinsertDataView"
            style="height: 50px;background: #007AFF;line-height: 50px;text-align: center;color: #ffffff;font-weight: bold;">
            提交</div>
        </div>
      </van-tab>
      <van-tab title="过程信息">
        <FileData :ROW_GUID="row.ROW_GUID" :rowData="row"></FileData>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script>
import { QuerySignCallback, FileServerUpload, GetFileData, DelectFile, FileServerProxy } from '@/utils/api'
import FileData from '@/components/activity/FileData'
export default {
  data() {
    return {
      formData: {
        APPLYTYPE: "",
        YDLX: "",
        DL_NYD: "",
        YDLX_NYD_QT: "",
        HOMESTEADAREA: "",
        HOUSEFLOORAREA: "",
        CONSTRUCITONADDRESS: "",
        EAST: "",
        SOUTH: "",
        WEST: "",
        NORTH: "",
        BUILDAREA: "",
        BUILDHEIGHT: "",
        BUILDSTOREY: "",
        STRUCTURETYPE: "",
        SPACING: "",
        EXTERIORCOLOR: "",
      },
      ENUM: {
        NYD: false,
        NYDARR: [],
        JFLX: false,
        JFLXARR: [],
        YDLX: false,
        YDLXARR: [],
        JGLX: false,
        JGLXARR: [],
      },
      fileData: [
        {
          name: "踏勘照片1",
          groupGuid: "39150119-0da6-494a-b1e9-4bed532fecfd",
          fileList: [],
        },
        {
          name: "踏勘照片2",
          groupGuid: "fb00616c-0c03-41dc-b00b-84d3efe3af87",
          fileList: [],
        },
        {
          name: "踏勘照片3",
          groupGuid: "7cb50c01-d2e1-4119-a0b6-b0443daca71e",
          fileList: [],
        },
        {
          name: "坐标文件",
          groupGuid: "ad2bd6ce-ff46-4a19-a6b1-cfc0bbd64daf",
          fileList: [],
        },
        {
          name: "坐标串",
          groupGuid: "725b5997-51d2-4381-937a-4d826c2a3406",
          fileList: [],
        },
        {
          name: "宅基地坐落平面位置图",
          groupGuid: "be6c2622-e00f-49ca-b59d-2550fa62fef6",
          fileList: [],
        },
      ],
      showPickerq: false,
    }
  },
  components: {
    FileData
  },
  watch: {},
  filters: {
    inUseName: function (msg, data) {
      let name = "";
      data.forEach((item) => {
        if (item.DICID == msg) {
          name = item.DICNAME;
        }
      });
      return name;
    },
  },
  methods: {
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
    },
    //下拉时间选择
    onConfirmRQ(val) {
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      let hour = val.getHours();
      let minute = val.getMinutes();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      this.formData.CLSJ = `${year}-${month}-${day}`;
      this.showPickerq = false;
    },

    onConfirm1(value) {
      this.formData.APPLYTYPE = value.DICID;
      this.ENUM.JFLX = false;
    },
    onConfirm2(value) {
      this.formData.YDLX = value.DICID;
      this.ENUM.YDLX = false;
    },
    onConfirm3(value) {
      this.formData.STRUCTURETYPE = value.DICID;
      this.ENUM.JGLX = false;
    },
    onConfirm5(value) {
      this.formData.DL_NYD = value.DICID;
      this.ENUM.NYD = false;
    },
    //获取相关材料
    getFile: async function () {
      let groupGuid = [];
      this.fileData.forEach((item) => {
        groupGuid.push(item.groupGuid);
      });
      const res1 = await GetFileData({
        groupGuid: groupGuid.join(","),
        toRowGuid: this.rowGuid,
      });
      if (res1.data.FilesInfo.length > 0) {
        res1.data.FilesInfo.forEach((element) => {
          this.fileData.forEach((item) => {
            if (element.GROUPGUID == item.groupGuid) {
              if (item.name == '坐标文件' || item.name == '坐标串') {
                element["isImage"] = false;
                element['file'] = {
                  name: element.FILENAME
                }
              } else {
                element["isImage"] = true;
              }
              element["url"] = window.g.BaseURL + "FileServer/api/Preview?token=" + window.localStorage.getItem("token") + "&" + "fileGuid=" + encodeURIComponent(element.ROW_GUID);
              item.fileList.push(element);
            }
          });
        });
      }
    },
    //相关材料
    getList(item) {
      this.groupGuids = item.groupGuid;
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      this.getFileServerUpload(file.file);
    },
    //预览上传附件
    lookFile(item) {
      if (item.isImage == false) {
        ZWJSBridge.openLink({
          "url": item.url
        }).then(res => {
        }).catch(err => {
          window.open(item.url)
        })
      }
    },
    //删除附件
    delectFile: async function (file) {
      let fileguid = "";
      if (file.ROW_GUID) {
        fileguid = file.ROW_GUID;
      } else {
        fileguid = this.fileGuid;
      }
      if (fileguid) {
        let params = {
          accessCode: "ce9b691634de4ebca68dc5bb638d07f4",
          cityCode: window.localStorage.getItem("citycode")
            ? window.localStorage.getItem("citycode")
            : "441300000000",
          params: {
            fileGuid: fileguid,
            token: window.localStorage.getItem("token"),
          },
        };
        const res = await FileServerProxy(params);
        let data = JSON.parse(res.data.data).Success;
        if (data) {
          this.$toast.success("删除成功!");
        }
      }
    },
    // delectFile: async function (file) {
    //   if (file.ROW_GUID) {
    //     const res = await DelectFile({
    //       fileGuid: file.ROW_GUID,
    //       token: window.localStorage.getItem("token"),
    //     });
    //   }
    // },
    //上传附件
    getFileServerUpload: async function (file) {
      let formData = new FormData();
      formData.append("file", file);
      formData.append("toRowGuid", this.rowGuid);
      formData.append("groupGuid", this.groupGuids);
      formData.append("token", window.localStorage.getItem("token"));
      const res = await FileServerUpload(formData);
      if (res.data.Success == true) {
        this.$toast.success("上传成功!");
        this.fileData.forEach((item, index) => {
          item.fileList = [];
        });
        this.getFile();
      }
    },
    getNowTime: function () {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let dd =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd;
      return dateTime;
    },
    //提交
    getinsertDataView: async function () {
      let me = this
      let state = true
      me.fileData.forEach((item, index) => {
        if (item.fileList.length == 0) {
          if (item.name == '坐标串' || item.name == '坐标文件') {
            me.$toast.success('请上传附件！')
            state = false
          }
        }
      })
      if (state) {
        if (me.formData.APPLYTYPE && me.formData.YDLX && me.formData.HOMESTEADAREA && me.formData.HOUSEFLOORAREA && me.formData.CONSTRUCITONADDRESS
          && me.formData.EAST && me.formData.SOUTH && me.formData.WEST && me.formData.NORTH && me.formData.BUILDAREA && me.formData.BUILDHEIGHT
          && me.formData.BUILDSTOREY && me.formData.STRUCTURETYPE && me.formData.SPACING && me.formData.EXTERIORCOLOR) {
          let accessCode = '77ad6c1591e54d4fbc45ecc90374a2a2'
          if (!me.formData.ROW_GUID) {
            accessCode = '0fb3f6123d1b4fe6851c99532c463f6f'
            me.formData['ROW_GUID'] = me.rowGuid
            me.formData['TO_ROW_GUID'] = me.row.ROW_GUID
          }
          let params = {
            dataGuid: "a0e224e8-36be-4591-b770-30cabda3514a",
            strParams: JSON.stringify([me.formData]),
            token: window.localStorage.getItem('token')
          }
          let params1 = {
            accessCode: accessCode,

            cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
            params: params
          }
          const res = await QuerySignCallback(params1)
          if (eval('(' + res.data.data + ')').Success == true) {
            me.$toast.success('成功！')
            this.$router.push({
              path: '/SendOut',
              query: { data: JSON.stringify(this.row) }
            })
          } else {
            me.$toast.fail(res.data.msg)
          }
        } else {
          me.$toast.success('请输入必填项！')
        }
      }
    },
    //获取界面所需字典值
    getEnum: async function (viewID) {
      let _this = this;
      let params = {
        dataguid: viewID,
        searchObject: JSON.stringify([]),
        token: window.localStorage.getItem('token')
      }
      let params1 = {
        accessCode: '688bd3883572440a859dfd8ba9194e7b',

        params: params
      }
      const res = await QuerySignCallback(params1)
      let data = eval('(' + res.data.data + ')').Data
      switch (viewID) {
        case "db35edee-88e0-4fae-b14a-868ed4beb1d9":
          this.ENUM.JFLXARR = data;
          break;
        case "52215e71-341a-452b-8823-a8d4aae058ab":
          this.ENUM.NYDARR = data;
          break;
        case "d2ec96d4-b5bc-404a-a9f1-34db915c694b":
          this.ENUM.YDLXARR = data;
          break;
        case "b65d1943-66f4-49b1-b759-cd9f079dc0d3":
          this.ENUM.JGLXARR = data;
          break;
        default:
          break;
      }
    },
    getData: async function () {
      //查询信息
      let params = {
        dataguid: "a0e224e8-36be-4591-b770-30cabda3514a",
        searchObject: JSON.stringify([{ field: 'TO_ROW_GUID', value: this.row.ROW_GUID, link: 'OR', operator: '=' }]),
        token: window.localStorage.getItem('token')
      }
      let params1 = {
        accessCode: '688bd3883572440a859dfd8ba9194e7b',

        params: params
      }
      const res = await QuerySignCallback(params1)
      let data = eval('(' + res.data.data + ')').Data
      if (data.length > 0) {
        this.formData = data[0];
        this.formData.CLSJ = this.formData.CLSJ ? this.formData.CLSJ.split(" ")[0] : ""
        this.rowGuid = this.formData.ROW_GUID
        this.getFile();
      } else {
        this.formData.CLSJ = this.getNowTime()
        this.rowGuid = this.newGuid();
      }
    }
  },
  mounted() {
    this.row = JSON.parse(this.$route.query.data)
    this.getData()
    this.getEnum("52215e71-341a-452b-8823-a8d4aae058ab");
    this.getEnum("db35edee-88e0-4fae-b14a-868ed4beb1d9");
    this.getEnum("d2ec96d4-b5bc-404a-a9f1-34db915c694b");
    this.getEnum("b65d1943-66f4-49b1-b759-cd9f079dc0d3");
    if (ZWJSBridge) {
      ZWJSBridge.setTitle({
        "title": "现场踏勘"
      }).then(res => {
      }).catch(err => {
      })
    }
  },
}
</script>
<style scoped lang="scss">
#SiteSurvey {
  height: 100vh;
  overflow: auto;
  background: #f6f6f6;
  font-size: 14px;

  .top {
    height: 90px;
    background: #ffffff;
    margin-bottom: 20px;
    padding-top: 25px;
    text-align: center;
    font-size: 14px;
  }

  .content {
    width: 100%;
    height: auto;
    background: #ffffff;
    padding: 10px;

    .inputWrap {
      width: 100%;
      display: flex;
      justify-content: center;
      border-bottom: 1px solid #ebedf0;

      &>span {
        margin-right: 5px;
        margin-top: 15px;
      }
    }
  }
}
</style>
<style lang="scss">
#SiteSurvey {
  .van-cell {
    padding: 10px 0;
    font-size: 16px;
  }

  .van-field__label {
    width: auto !important;
  }

  .van-field__control {
    text-align: right;
  }
}
</style>
